package com.amox.uitest;

import java.io.File;
import java.io.FilenameFilter;
import java.util.Arrays;

import org.dom4j.Document;

import com.amox.uitest.common.KeyWord;
import com.amox.uitest.kit.LogKit;
import com.amox.uitest.kit.XMLKit;
import com.amox.uitest.tcase.BaseTestCase;

public class Rocket extends BaseTestCase {
	
	public final String OpenSetting_Command = "am start -n com.android.settings/com.android.settings.Settings";

	private final String CONFIG_PATH = "conf";
	
	@Override
	public void play() throws Exception {
		
		String highPath = getCurPath() + CONFIG_PATH;
		// 1. 加载指定目录下的所有xml文件
		File[] amScripts = getSubFiles(highPath);
		
		if(amScripts.length == 0) {
			LogKit.printLog("[ERROR] The Script File Is Not Found !");
			LogKit.printLog("[ERROR] The Script File's Name, Such As uitest-*-"
					+ bundle.getString("mode") + ".xml !");
		}
		
		for(File file : amScripts) {
			LogKit.printLog("Starting Load File[{0}] ...", file.getName());
			String fileName = file.getName().toLowerCase();
			
//			if(fileName.endsWith( + ".xml")) {
				execXML(file);
//			}
			
			System.out.println();
			LogKit.printLog("Finished Load File[{0}] !", file.getName());
			sleep(3000);
		}
	}

	private void execXML(File file) throws Exception {
		Document document = XMLKit.me(this).readAsDoc(file);
		if(!XMLKit.me(this).isStandard(document)) {
			LogKit.printLog("ERROR : The File[{0}] Is Not a Standard XML File, The Program Is Interrupted !", file.getName());
			return;
		}
		
		XMLKit.me(this).exec(document);
	}
	
	/**
	 * get current path
	 * @return
	 */
	public String getCurPath() {
		String path = System.getProperty("java.class.path");
		int firstIndex = path.lastIndexOf(System.getProperty("path.separator")) + 1;
		int lastIndex = path.lastIndexOf(File.separator) + 1;
		path = path.substring(firstIndex, lastIndex);
		return path;
	}
	
	/**
	 * get children files
	 * @param highPath
	 * @return
	 */
	public File[] getSubFiles(String highPath) {
		File highFile = new File(highPath);
		
		if(!(highFile.isDirectory() && highFile.exists())) {
			highFile = new File(getCurPath());
		}
		
		// filte file with the suffix
		File[] amScripts = highFile.listFiles(new FilenameFilter() {
		    @Override
		    public boolean accept(File dir, String name) {
		        return name.startsWith(KeyWord.uitest.name() + "-") 
		        		&& name.endsWith(bundle.getString("mode") + ".xml");
		    }
		});
		
		// order by name asc
		Arrays.sort(amScripts);
		
		return amScripts;
	}

}
